package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.constant.EsConstant;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.mapper.ItemMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.Item;

import cn.itcast.hotel.pojo.ItemDoc;
import cn.itcast.hotel.service.ItemService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
@Slf4j
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements ItemService {
    @Autowired
    RestHighLevelClient client;

    @Autowired
    ItemMapper itemMapper;

    @Override
    public void itemPage() throws IOException {
        Page<Item> page = new Page<>(1, 1000);
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        IPage<Item> itemIPage = itemMapper.selectPage(page, queryWrapper);
        List<Item> items = itemIPage.getRecords();
        BulkRequest bulkRequest = new BulkRequest();
        for (Item item : items) {
            ItemDoc doc = new ItemDoc(item);
            IndexRequest indexRequest = new IndexRequest(EsConstant.INDEX_ITEM_NAME).id("" + item.getId());
            indexRequest.source(JSON.toJSONString(doc), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        boolean failures = bulkResponse.hasFailures();
        if (failures) {
            String message = bulkResponse.buildFailureMessage();
            log.error("导入异常，message:{}", message);
        } else {
            int number = bulkRequest.numberOfActions();
            log.error("导入成功的记录条数:{}", number);
        }
    }
}